import { computed, ref, watch } from "vue";
import { useStore } from "vuex";
import { createGlobalState, useAsyncState } from "@vueuse/core";
import request from "../../common/utils/request";
import utils from "../../common/utils/utils";

export const useTeamId = () => {
  const store = useStore();

  const teamId = ref(store.state.user.teamId);

  watch(
    () => store.state.user.teamId,
    (pTeamId) => {
      teamId.value = pTeamId;
    }
  );

  const changeTeamId = async (pTeamId) => {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      const match = key.match(new RegExp(`^LASTORG_(\\d+)_LASTUID_(\\d+)$`));
      if (match) {
        const last_orgId = match[1];
        const last_uid = match[2];
        let now_orgId = utils.getOrgId();
        let now_uId = "";

        const now_userInfo = await utils.getUserInfo();
        if (now_userInfo.uid) {
          now_uId = String(now_userInfo.uid);
        }
        if (last_orgId == now_orgId && last_uid == now_uId) {
          localStorage.setItem(
            "LASTORG_" + now_orgId + "_LASTUID_" + now_uId,
            pTeamId
          );
        }
      }
    }
    await store.dispatch("SetTeamId", pTeamId);
  };

  return [teamId, changeTeamId];
};

export const useSinger = () => {
  let person = {
    id: 0,
    name: "个人",
  };

  const store = useStore();
  const singer = ref(person);

  const setSigner = (userInfo) => {
    if (userInfo.avatar) {
      singer.value = {
        ...person,
        name: userInfo.nickname,
        avatar: userInfo.avatar,
        user_id: userInfo.id,
      };
    } else {
      singer.value = person;
    }
  };

  watch(store.state.user.userInfo, (userInfo) => {
    setSigner(userInfo);
  });

  if (store.state.user.userInFo) {
    setSigner(store.state.user.userInFo);
  }

  return [singer];
};

export const useTeamState = createGlobalState(() => {
  const store = useStore();
  const {
    state: teamList,
    isLoading,
    execute,
  } = useAsyncState((args) => {
    if (!store.getters.isLogin) {
      return Promise.resolve([]);
    }
    return request
      .get("/work_ai", "/user/team/list", {})
      .then((res) => res.list);
  }, []);

  watch(
    () => store.getters.isLogin,
    (isLogin) => {
      if (isLogin && teamList.value.length == 0) {
        execute();
      }
    }
  );

  return {
    teamList,
    isLoading,
    execute,
  };
});

export const useTeam = () => {
  const teamState = useTeamState();
  const [teamId, changeTeamId] = useTeamId();
  const [singer] = useSinger();

  const teams = computed(() => {
    return [singer.value].concat(teamState.teamList.value);
  });

  const currentTeam = computed(() => {
    return teams.value.find((item) => item.id == teamId.value) || singer.value;
  });

  return {
    teams,
    changeTeamId,
    currentTeam,
  };
};
